import React, { useContext } from 'react'
import './index.scss'
import { ContextCount } from '../../App'
export default function MyCount ({ count, id }) {
  // 3拿到数据
  const { changeCount } = useContext(ContextCount)
  const handleDecrease = () => {
    // !#2. 子组件调用传递过来的方法并传递实参
    if (count <= 1) return
    changeCount(id, count - 1)
  }
  const handleIncrease = () => {
    changeCount(id, count + 1)
  }
  const handleChange = (e) => {
    if (!/^[1-9]\d*$/.test(e.target.value)) return
    changeCount(id, +e.target.value)

  }
  return (
    <div className='my-counter'>
      <button type='button' className='btn btn-light' onClick={handleDecrease}>
        -
      </button>
      <input
        type='number'
        className='form-control inp'
        value={count}
        onChange={handleChange}
      />
      <button type='button' className='btn btn-light' onClick={handleIncrease}>
        +
      </button>
    </div>
  )
}